import Koa from "koa";
import Router from "koa-router";
import bodyParser from "koa-bodyparser";
import cors from "@koa/cors";
import { ApiResponse } from "./utils/response";
import userData from "./data/user.json";

const app = new Koa();
const router = new Router();

// 配置 CORS 中间件
app.use(
  cors({
    origin: (ctx) => {
      const requestOrigin = ctx.request.header.origin;
      if (requestOrigin && new URL(requestOrigin).hostname === ctx.hostname) {
        return requestOrigin;
      }
      return '*';
    },
    credentials: true,
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  })
);

// 中间件
app.use(bodyParser());

// 默认路由 - 根路径
router.get("/", async (ctx) => {
  ctx.body = ApiResponse.info({
    "/": "GET - 当前接口，显示服务器状态",
    "/api/hello": "GET - 返回问候消息",
    "/api/echo": "POST - 回显发送的数据",
  });
});

// 路由
router.get("/api/list", async (ctx) => {
  ctx.body = ApiResponse.success([1, 2, 3]);
});

// 添加获取用户列表接口
router.get("/api/user", async (ctx) => {
  const { users } = userData;
  ctx.body = ApiResponse.success_page(users, 10);
});

// 注册路由
app.use(router.routes()).use(router.allowedMethods());

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
